package Compile;

import Common.FileUtil;

import java.io.File;
import java.io.IOException;

public class Task {

    private static final String WORK_DIR = "./tmp/";
    private static final String CLASS = "Solution";
    private static final String CODE = WORK_DIR + "Solution.java";
    private static final String COMPILE_ERROR = WORK_DIR + "compileError.txt";
    private static final String STDOUT = WORK_DIR + "stdout.txt";
    private static final String STDERR = WORK_DIR + "stderr.txt";

    public Answer compileAndRun(Question question) throws IOException, InterruptedException {
        Answer answer = new Answer();
        // 0. 准备好存放临时文件的目录
        File workDir = new File(WORK_DIR);
        if (!workDir.exists()) {
            workDir.mkdir();
        }
        // 1. 根据 Compile.Question 创建临时文件
        FileUtil.writeFile(CODE, question.getCode());
        // 2. 构造编译命令, 并执行
        //    javac -d 用来指定生成的 .class 文件的位置.
        String compileCmd = String.format(
                "javac -encoding utf8 %s -d %s",
                CODE, WORK_DIR);
        System.out.println("编译命令: " + compileCmd);
        Commandutil.run(compileCmd, null, COMPILE_ERROR);
        // 判定下编译是否成功, 看得到的编译错误文件是否为空文件即可
        String compileError = FileUtil.readFile(COMPILE_ERROR);
        if (!compileError.equals("")) {
            System.out.println("编译出错!");
            answer.setError(1);
            answer.setReason(compileError);
            return answer;
        }
        // 3. 构造运行命令, 并执行
        String runCmd = String.format(
                "java -classpath %s %s", WORK_DIR, CLASS
        );
        System.out.println("运行命令: " + runCmd);
        Commandutil.run(runCmd, STDOUT, STDERR);
        // 判定下运行是否出错
        String runError = FileUtil.readFile(STDERR);
        if (!runError.equals("")) {
            System.out.println("运行出错!");
            answer.setError(2);
            answer.setReason(runError);
            return answer;
        }
        // 4. 将运行结构包装到最终 Compile.Answer 对象中
        answer.setError(0);
        answer.setStdout(FileUtil.readFile(STDOUT));
        return answer;
    }

    public static void main(String[] args) throws IOException, InterruptedException {
        Question question = new Question();
        question.setCode(
                "public class Solution {\n" +
                        "   public static void main(String[] args) {\n" +
                        "       System.out.println(\"hello\");\n" +
                        "   }\n" +
                        "}\n");
        Task task = new Task();
        Answer answer = task.compileAndRun(question);
        System.out.println(answer);
    }

}
